import time
import json
from UAS import memetic_workflow

def run_test(params, target_profit=10):
    """运行单次测试，使用MemeticWorkflow类"""
    start_time = time.time()
    
    # 创建并配置工作流
    workflow = memetic_workflow.MemeticWorkflow()
    workflow.config.update({
        'population_size': params['population_size'],
        'max_iterations': params['max_iterations'],
        'max_mutation_prob': params['max_mutation_prob'],
        'min_mutation_prob': params['min_mutation_prob'],
        'performance_mode': True,
        'time_limit': params['time_limit'],
        'valid_time': params['valid_time'],
        'penalty_interval': 10,
        'penalty_rate': 10,
        'points_path': 'd:/Work/Projects/UAS/valid_points - Chao 66.xlsx',
        'matrix_path': 'd:/Work/Projects/UAS/valid_matrix - Chao 66.xlsx',
        #'points_path': 'd:/Work/Projects/UAS/valid_points - Tsiligirides 3.xlsx',
        #'matrix_path': 'd:/Work/Projects/UAS/valid_matrix - Tsiligirides 3.xlsx',
        'data_path': 'd:/Work/Projects/UAS/'
    })
    
    # 执行工作流
    results = workflow.run_workflow()
    
    elapsed_time = time.time() - start_time
    
    # 处理返回结果
    test_result = {
        'params': params,
        'reached_target': results[0].total_profit >= target_profit if results else False,
        'best_profit': results[0].total_profit if results else 0,
        'time_elapsed': elapsed_time,
        'iterations_used': workflow.config['max_iterations']
    }
    
    return test_result

def parameter_test():
    # 参数测试主函数
    
    # 测试参数范围
    param_ranges = {
        'population_size': [60],#[30, 50, 100, 200],
        'max_iterations': [30, 50, 100, 200],# 50, 100, 200],#[30, 50, 100, 200],
        'max_mutation_prob': [0.2],#[0.01, 0.02, 0.05, 0.1, 0.2],
        'min_mutation_prob': [0.01]#[0.01, 0.02, 0.05, 0.1, 0.2]
    }
    
    # Tmax参数范围 (5到130，步长5)
    tmax_params = range(5, 130, 5)
    #tmax_params = [40]
    
    # 存储所有测试结果
    all_results = []
    
    # 遍历Tmax参数
    for tmax in tmax_params:
        print(f"\n=== Testing with Tmax={tmax} ===")
        
        # 遍历所有参数组合
        for pop_size in param_ranges['population_size']:
            for max_iter in param_ranges['max_iterations']:
                for mut_prob in param_ranges['max_mutation_prob']:
                    print(f"\nTesting: pop_size={pop_size}, max_iter={max_iter}, mut_prob={mut_prob}")
                    
                    # 确保min_mutation_prob ≤ max_mutation_prob
                    for min_mut in [m for m in param_ranges['min_mutation_prob'] if m <= mut_prob]:
                        params = {
                            'population_size': pop_size,
                            'max_iterations': max_iter,
                            'max_mutation_prob': mut_prob,
                            'min_mutation_prob': min_mut,
                            'time_limit': tmax * 10,
                            'valid_time': tmax * 10
                        }
                    
                        # 每个组合运行10次
                        for i in range(10):
                            print(f"Run {i+1}/10...", end=' ')
                            result = run_test(params)
                            all_results.append(result)
                            
                            if result['reached_target']:
                                print(f"Success! Profit={result['best_profit']}, Time={result['time_elapsed']:.2f}s")
                            else:
                                print(f"Failed. Profit={result['best_profit']}")
        
        # 保存结果
        filename = f'results/Chao66_Tmax{tmax}_pop60_max02_min001.json'
        with open(filename, 'w') as f:
            json.dump(all_results, f, indent=4)
            print(f"\nResults saved to {filename}")
        
        # 清空结果列表准备下一次循环
        all_results = []
    
    print("\nAll tests completed.")

if __name__ == "__main__":
    parameter_test()
